package org.jground.rx.ui.zk.viewControl;

import java.util.List;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jground.rx.IRXObject;
import org.jground.rx.IRXObjectSynopsis;
import org.jground.rx.IRXObjectUtils;
import org.jground.rx.RXAccess;
import org.jground.rx.RXAttribute;
import org.jground.rx.RXClass;
import org.jground.rx.RXSystem;
import org.jground.rx.RXTypeRef;
import org.jground.rx.RXView;
import org.jground.rx.ui.zk.UIDataObjectRefSearchPanel;
import org.jground.rx.ui.zk.UIFrame;
import org.jground.rx.ui.zk.UIResultList;
import org.jground.rx.ui.zk.UIStyles;
import org.jground.util.ArrayUtils;
import org.jground.util.CollectionUtils;
import org.jground.zk.zulX.HboxX;
import org.jground.zk.zulX.VboxX;
import org.zkoss.zk.ui.event.Event;
import org.zkoss.zk.ui.event.EventListener;
import org.zkoss.zk.ui.event.Events;
import org.zkoss.zul.Button;
import org.zkoss.zul.Listcell;
import org.zkoss.zul.Listitem;
import org.zkoss.zul.ListitemRenderer;

public class UIAttributeControlRef extends UIAttributeControlBase implements EventListener {

    /**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static Log logger = LogFactory.getLog(UIAttributeControlRef.class);

    public UIAttributeControlRef createNew(UIFrame uiFrame, RXView moControl) {
        return new UIAttributeControlRef(uiFrame, moControl);
    }

    //
    public UIAttributeControlRef() {}

    private UIResultList resultList;
    private Button lookupBt;
    private Button newBt;
    private String refMoid;
    private RXAttribute moAttribute;
    private boolean isMultiple;
    private RXTypeRef refType;
    //
    private UIDataObjectRefSearchPanel refSearchPanel;

    // private UIEditWindow refEditWindow;

    // HListSelectionPanel<IRXObject>

    private UIAttributeControlRef(UIFrame uiFrame, RXView rxControl) {
        super(uiFrame, rxControl);
        logger.debug("init UIAttributeControlRef");
        this.moAttribute = rxControl.getRXAttribute();
        refType = (RXTypeRef) moAttribute.getRXType().getBaseType();
        refMoid = refType.getLookupMoid();
        isMultiple = moAttribute.getRXType().isMultiple();
        resultList = new UIResultList(uiFrame);
        resultList.setPostfixRenderer(new PostfixRenderer());
        //
        HboxX buttonPanel = null;
        lookupBt = new Button("Lookup ...");
        newBt = new Button("New ...");
        //
        if (RXAccess.getInstance().canCreate(RXSystem.getInstance().getRxService().getRXClass(refMoid))) {
            buttonPanel = UIHelper.createButtonPanel(lookupBt, newBt);
        } else {
            buttonPanel = UIHelper.createButtonPanel(lookupBt);
        }
        //
        super.add(new VboxX(UIResultList.uiBox(resultList), buttonPanel));
        //
        lookupBt.addEventListener(Events.ON_CLICK, this);
    }

    @Override
    public void set(String... values) {
        clear();
        if (ArrayUtils.isNotEmpty(values)) {
            resultList.addObjects(IRXObjectUtils.oidsToRXDataObjectArray(values));
        }
    }

    @Override
    public String[] get() {
        return IRXObjectUtils.toOidStringArray(resultList.getObjects());
    }

    @Override
    public void clear() {
        resultList.removeAllObject();
    }

    public void onEvent(Event he) {
        if (he.getTarget() == newBt) {
            // if (refEditWindow == null) {
            // refEditWindow = new UIEditWindow(uiFrame, refMoid);
            // }
            // RXClass moClass = RXSystem.getInstance().getRxService().getRXClass(refMoid);
            // String className = moClass.getName();
            // Set<String> submoids = null;
            // if (refType.subClasses()) {
            // submoids = moClass.getAllRXSubClasses();
            // } else {
            // submoids = SetUtils.asSet(refMoid);
            // }
            // //
            // refSearchPanel.reInit(className + " :: Search for " +
            // moAttribute.getLabel(), isMultiple, this,
            // resultList.getObjects(),
            // submoids.toArray(StringUtils.EMPTY_STRING_ARRAY));
            // uiFrame.setMainPanel(refSearchPanel, true);
        }
        if (he.getTarget() == lookupBt) {
            refSearchPanel = uiFrame.getRefSearchPanel();
            RXClass refClass = RXSystem.getInstance().getRxService().getRXClass(refMoid);
            String className = refClass.getName();
            //
            refSearchPanel.reInit(className + " :: Search for " + moAttribute.getLabel(), isMultiple, this, resultList.getObjects(), refType, getDataContext());
            uiFrame.setMainPanel(refSearchPanel, true);
        }
        if (refSearchPanel != null && he.getTarget() == refSearchPanel.getView()) {
            if (he.getName() == UIDataObjectRefSearchPanel.ON_DONE) {
                List<IRXObjectSynopsis> mods = refSearchPanel.getSelected();
                if (CollectionUtils.isNotEmpty(mods)) {
                    if (isMultiple) {
                        for (IRXObjectSynopsis mod : mods) {
                            resultList.addObjects(mod);
                        }
                    } else if (resultList.getObjects().size() == 0) {
                        resultList.addObjects(mods.get(0));
                    }
                }
            }
            if (he.getName() == UIDataObjectRefSearchPanel.ON_CANCEL) {
                // nothing to do
            }
            uiFrame.closeMainPanel(refSearchPanel);
        }
    }

    public class PostfixRenderer implements ListitemRenderer, EventListener {

        public void render(Listitem item, Object data) throws Exception {
            if (data instanceof IRXObject) {
                IRXObject mod = (IRXObject) data;
                Listcell c = null;
                c = new Listcell();
                c.setParent(item);
                c.setImageContent(UIStyles.getInstance().getAImage(UIStyles.ImageKey.delete16));
                c.addEventListener(Events.ON_CLICK, this);
                c.setAttribute("mod", mod);
            }
        }

        public void onEvent(Event h) {
            // if (h.getTarget() instanceof Button) {
            // Button b = (Button) h.getTarget();
            // IRXObject mod = (IRXObject) b.getAttribute("mod");
            // dataList.removeObject(mod);
            // }
            if (h.getTarget() instanceof Listcell) {
                Listcell b = (Listcell) h.getTarget();
                IRXObject mod = (IRXObject) b.getAttribute("mod");
                resultList.removeObject(mod);
            }
        }

    }
}